<template>
    <el-upload
      :fileList="fileList"
      class="custom-upload"
      :action="uploadURL + '/file/upload/fileUpload'"
      :before-upload="beforeUpload" 
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-remove="handleRemove"
    >
      <el-icon style="font-size:48px; color:#409eff"><UploadFilled /></el-icon>
      <div class="el-upload__text">
            拖入需要上传的文件或点击上传
      </div>
      <div class="el-upload__text" style="font-size:12px;">
          支持扩展名:{{ info }}
      </div>
      <template #tip>
        <div class="el-upload__tip" style="font-size:12px;">
            {{ text || '' }}
        </div>
      </template>
    </el-upload>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { ref, reactive, watch, onMounted, computed, nextTick } from 'vue';
import { WarningFilled, UploadFilled } from '@element-plus/icons-vue';
import { uploadURL } from '@/utils/axios';
const props = defineProps({
    text:String,
    allowTypes:Array,
    maxSize:Number,
    field:String
})
const fileList = ref([]);
const applyFiles = ref('');
const info = computed(()=>{
  return props.allowTypes.join(' / ') + ', 最大' + props.maxSize + 'MB'
})
const emit = defineEmits(['on-select']);
const fileTypes = {
    'jpeg':1,
    'jpg':1,
    'png':1,
    'gif':1,
    'pdf':1,
    'doc':1,
    'docx':1,
    'ppt':1,
    'pptx':1,
    'xls':1,
    'xlsx':1,
    'md':1,
    'mp4':1,
    'ogg':1,
    'flv':1,
    'avi':1,
    'wmv':1
}
const beforeUpload = (file) => {
    let temp = file.name.split('.');
    let fileType = temp.length ? temp[temp.length - 1].toLowerCase() : '';
    let isLess = file.size / 1024 / 1024 < props.maxSize;
    if ( applyFiles.value ) {
        ElMessage.error('文件已上传');
        return false;
    }
    if ( !fileTypes[fileType] || !props.allowTypes.includes(fileType) ){
        ElMessage.error('文件类型不支持');
        return false;
    }
    if ( !isLess ) {
        ElMessage.error('文件不能超过20mb');
        return false;
    }
    return true;
}
function init(filePath){
  let temp = filePath.split('_');
  let fileName = temp.length ? temp[temp.length - 1] : '';
  fileList.value = [{ name:fileName, url:filePath }];
  applyFiles.value = filePath;
}
defineExpose({
    init
})
const handleSuccess = (response, uploadFile) => {
    // 资源上传成功将路径传递给父组件的状态
    // imageUrl.value = URL.createObjectURL(uploadFile.raw);
    // console.log(uploadFile);
    // console.log(response);
    let path = response.data.length ? response.data[0].logoPath : '';
    applyFiles.value = path;
    // console.log(path);
    emit('on-select', props.field, path);
}
const handleError = ()=>{
  // console.log('error...');
}
const handleRemove = (file)=>{
  // console.log('remove...', file);
  if ( file.status === 'success') {
    applyFiles.value = '';
  }
 
}

</script>
<style>
  .custom-upload .el-upload {
    width:340px;
  }
  .custom-upload .el-upload-list {
    width:340px !important;
  }
</style>